package cn.chendd.utils;

import java.awt.Component;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;

import cn.chendd.patch.vo.DataVo;

/**
 * <pre>
 * 公共工具类
 * </pre>
 *
 * <pre>
 * modify by chendd on 2017-6-20
 *    fix->1.
 *         2.
 * </pre>
 */
public class CommonUtil {
	
	public static List<String> getListByFile(File file , int startRowIndex) throws IOException{
		String fileName = file.getName();
		int index = fileName.lastIndexOf(".");
		List<List<String>> dataList = null;
		String suffix = fileName.substring(index + 1, fileName.length());
		if("csv".equalsIgnoreCase(suffix)){
			dataList = getListByCsv(file , startRowIndex);
		} else if("txt".equalsIgnoreCase(suffix)){
			List<String > lineList = FileUtils.readLines(file);
			return lineList;
		} else{
			//excel
			dataList = ExcelUtil.getListByExcel(file , startRowIndex);
		}
		List<String> newList = new ArrayList<String>();
		for (List<String> list : dataList) {
			if(list != null && !list.isEmpty()){
				newList.add(list.get(0));
			}
		}
		return newList;
	}
	
	/**
	 * 读取CSV文件,将文件读取的结果转换为集合类型
	 * @param file csv文件
	 * @param startRowIndex 读取文件的开始行
	 * @return 集合数据
	 * @throws Exception 读取csv异常
	 */
	public static List<List<String>> getListByCsv(File file, int startRowIndex) throws IOException{
		ICsvListReader reader = null;
		List<List<String>> dataList = null;
		try {
			reader = new CsvListReader(new FileReader(file), CsvPreference.EXCEL_PREFERENCE);
			dataList = new ArrayList<List<String>>();
			List<String> lineList = new ArrayList<String>();
			int index = 0;
			while((lineList = reader.read()) != null){
				if(index == startRowIndex){
					index = startRowIndex;
					dataList.add(lineList);
					continue;
				}
				index++;
			}
		} catch (IOException e) {
			throw new IOException(e);
		} finally{
			CloseUtil.close(reader);
		}
		return dataList;
		
	}
	
	/**
	 * <pre>
	 * 将集合专户为二维数组
	 * </pre>
	 * @param dataList 集合类型
	 * @return 二维数组
	 */
	public static Object[][] listMap2Array(List<LinkedHashMap<String , Object>> dataList){
		
		Object obj[][] = null;
		if(dataList != null && dataList.isEmpty() == false){
			int size = dataList.size();
			obj = new Object[size][];
			for (int i=0 ; i < size ; i++) {
				Map<String, Object> map = dataList.get(i);
				Collection<Object> set = map.values();
				int lens = set.size();
				Object values[] = new Object[lens];
				Iterator<Object> it = set.iterator();
				int index = 0;
				while(it.hasNext()){
					Object value = it.next();
					values[index] = value;
					index++;
				}
				obj[i] = values;
			}
		}
		return obj;
	}
	
	/**
	 * <pre>
	 * 将集合专户为二维数组
	 * </pre>
	 * @param dataList 集合
	 * @return 二维数组
	 * @throws Exception 反射动态赋值异常
	 */
	public static Object[][] list2Array(List<? extends DataVo> dataList) {
		
		Object obj[][] = null;
		if(dataList == null || dataList.isEmpty()){
			return obj;
		}
		int size = dataList.size();
		obj = new Object[size][];
		for (int i=0 ; i < size ; i++) {
			DataVo vo = dataList.get(i);
			String props[] = vo.getPropSorts();
			int lens = props.length;
			Object values[] = new Object[lens];
			for(int j=0 ; j < lens ; j++){
				String prop = props[j];
				Object value = null;
				try {
					value = BeanUtils.getProperty(vo, prop);
				} catch (Exception e) {
					LogUtil.error(e);
					return null;
				}
				values[j] = value;
			}
			obj[i] = values;
		}
		return obj;
	}
	
	/**
	 * <pre>
	 * 将一个字符串替换，数组的偶数下标替换奇数下标
	 * </pre>
	 * @param input
	 * @param params
	 * @return
	 */
	public static String getReloadString(String input , String ...params){
		String text = null;
		if(StringUtils.isEmpty(input)){
			return text;
		}
		if(params != null){
			int lens = params.length;
			if(lens > 0 && lens % 2 == 0){
				for (int i=0 ; i < lens ; i=i+2) {
					String key = params[i];
					String value = params[i + 1];
					input = input.replace(key, value);
				}
			}
		}
		return input;
	}

	/**
	 * 打开文件选择对话框，从桌面开始选择文件
	 * @param title 窗口标题
	 * @param suffix 过滤后缀名
	 * @param frame jframe对象
	 * @return 选择文件的路径 ? null
	 */
	public static String getFileChooser(Component frame , String title , String ...suffix){
		JFileChooser chooser = new JFileChooser();
		StringBuilder descritionBuilder = new StringBuilder();
		for (String s : suffix) {
			descritionBuilder.append("*.").append(s).append(" 或 ");
		}
		if(descritionBuilder.length() > 0){
			descritionBuilder.deleteCharAt(descritionBuilder.length() - 2);
		}
		FileNameExtensionFilter filter = new FileNameExtensionFilter(descritionBuilder.toString(), suffix);
		FileSystemView systemView = FileSystemView.getFileSystemView();
		chooser.setCurrentDirectory(systemView.getHomeDirectory());
		chooser.setAcceptAllFileFilterUsed(false);
		chooser.setFileFilter(filter);
		chooser.setDialogTitle(title);
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int returnValue = chooser.showSaveDialog(frame);
		if(returnValue == JFileChooser.CANCEL_OPTION){
			return null;
		}
		File selectFile = chooser.getSelectedFile();
		if(selectFile.exists() && selectFile.isFile()){
			String filePath = selectFile.getPath();
			return filePath;
		}
		return null;
	}
	
	public static String getFileChooser(Component frame , String title , String fileName , String suffix){
		JFileChooser chooser = new JFileChooser();
		FileNameExtensionFilter filter = new FileNameExtensionFilter(fileName, suffix);
		FileSystemView systemView = FileSystemView.getFileSystemView();
		chooser.setCurrentDirectory(systemView.getHomeDirectory());
		chooser.setAcceptAllFileFilterUsed(false);
		chooser.setFileFilter(filter);
		chooser.setDialogTitle(title);
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int returnValue = chooser.showSaveDialog(frame);
		if(returnValue == JFileChooser.CANCEL_OPTION){
			return null;
		}
		File selectFile = chooser.getSelectedFile();
		if(selectFile.exists() && selectFile.isFile()){
			String filePath = selectFile.getPath();
			return filePath;
		}
		return null;
	}
	
	public static String getDirectoryChooser(Component frame , String title , String buttonText){
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		FileSystemView systemView = FileSystemView.getFileSystemView();
		chooser.setCurrentDirectory(systemView.getHomeDirectory());
		chooser.setDialogTitle(title);
		chooser.setApproveButtonText(buttonText);
		int returnCode = chooser.showOpenDialog(frame);
		if(returnCode == JFileChooser.CANCEL_OPTION){
			return null;
		}
		File selectFile = chooser.getSelectedFile();
		if(! selectFile.exists()){
			selectFile.mkdirs();
		}
		String filePath = selectFile.getPath();
		return filePath;
	}
	
}
